<style>
table.lo * { font-size: 12px; font-family: Trebuchet MS; }
table.lo { width: 100%; }
table.lo td { vertical-align: top; text-align: left; }
table.lo td.img { width: 330px; vertical-align: top; }
table.lo td.item { width: 400px; vertical-align: top; overflow-x: hidden; height: 50px; }
table.lo td.more { width: 220px; vertical-align: top; }
div.section { border-bottom: 1px dotted #000; word-wrap: break-word; width: 400px; }
div.title { font-size: 16px !important; font-weight: bold; font-family: Lucida Sans Unicode; padding-bottom: 5px; }
div.section div.bg { border: 1px solid #E7DBB1; background: #FFFEE6; padding: 5px; margin: 5px; }
div.section div.white { border: 1px solid #aaa !important; background: #fff !important; }
table.custom { width: 100%; }
table.custom td { height: 25px; color: #333; vertical-align: middle }
table.custom td.title { width: 100px; font-size: 13px; }
table.custom td.dot { color: #ff8000; }
table.custom td.mkt { text-decoration: line-through; font-size: 11px; color: #aaa; }
table.custom td.sale { font-size: 18px; color: #ff8000; font-weight: bold; }
div.form3 { scroll: none; background-color: #999; border: 1px solid #666; color: #fff; padding: 2px; cursor: pointer; margin-right: 5px; float: left; width: 35px; height: 20px; overflow: hidden; }
div.form3:hover { background: #eee; color: #333; }
div.hi { background-color: #fff; color: #000 }
.pure_button_cart { margin-left: 5px; font-weight: bold; font-size: 14px !important; }
#tabs a.tab { font-size: 14px; }
.pure_form_extra * { font-size: 12px !important; }
.pure_form_extra label { font-weight: bold; }
</style>

<?php
$id = Utils::get_param('id', 0);
$opts = new stdClass();
$opts->cd = 't.id = :v1';
$opts->cdv = array(':v1' => $id);
$data = $orm->get('pb_ecom_product', NULL, NULL, NULL, NULL, $opts)->d;
$images = array();
$attrs = array();
$myopts = array();
$pdobjs = array();
if (count($data) > 0) {
  $opts = new stdClass();
  $opts->cd = 't.product_track_id = :v1';
  $opts->cdv = array(':v1' => $data[0]->track_id);
  $images = $orm->get('pb_ecom_product_img', NULL, NULL, NULL, NULL, $opts)->d;
  $attrs = $orm->get('pb_ecom_product_attr', NULL, NULL, NULL, NULL, $opts)->d;
  $myopts = $orm->get('pb_ecom_product_attr_opt', NULL, NULL, NULL, NULL, $opts)->d;
  $pdobjs = $orm->get('pb_ecom_product_obj', NULL, NULL, NULL, NULL, $opts)->d;
}

$user = null;
if (isset($_SESSION['user'])) {
  $user = json_decode($_SESSION['user']);
}

$currs = $orm->get('pb_ecom_currency', 't.title', 'ASC', NULL, NULL, NULL)->d;

$cart = array();
if (isset($_SESSION['cart'])) {
  $cart = json_decode($_SESSION['cart']);
}
?>

<table class="lo" cellpadding="0" cellspacing="0">
  <tr>
    <td class="img">
      <ul id="etalage">
        <?php foreach ($images as &$image) { ?>
        <li>
          <img class="etalage_thumb_image" src="<?php echo $image->file; ?>">
          <img class="etalage_source_image" src="<?php echo $image->file; ?>">
        </li>
        <?php } ?>
      </ul>
    </td>
    <td class="item">
      <div class="section title"><?php echo $data[0]->name; ?></div>
      <div class="section">
        <div class="bg white" style="min-height: 100px;">
          <?php echo $data[0]->brief; ?>
        </div>
      </div>
      <div class="section">
        <div class="bg white">
          <span id="currs">
          <?php foreach ($currs as $itm) { ?>
            <input type="radio" id="curr_<?php echo $itm->title; ?>" onclick="update_curr(<?php echo $itm->id; ?>);" name="curr" /><label for="curr_<?php echo $itm->title; ?>"><?php echo $itm->display_name; ?></label>
           <?php } ?>
           </span>
          <table class="custom" cellpadding=0 cellspacing=0>
            <tr>
              <td class="dot">&#8226;</td>
              <td class="title">重量</td>
              <td class="weight"><?php echo $data[0]->weight; ?>kg</td>
            </tr>
            <tr>
              <td class="dot">&#8226;</td>
              <td class="title">市场价</td>
              <td class="mkt">&nbsp;</td>
            </tr>
            <tr>
              <td class="dot">&#8226;</td>
              <td class="title">销售价</td>
              <td class="sale">&nbsp;</td>
            </tr>
            <tr>
              <td class="dot">&#8226;</td>
              <td class="title">节省</td>
              <td class="save">&nbsp;</td>
            </tr>
          </table>
        </div>
      </div>
      <div class="section" style="border-bottom: none;">
        <div class="bg">
          <?php if (count($attrs) > 0) { ?>
          <div><b>选中:</b> <span id="selected"></span></div>
          <div>&nbsp;</div>
          <div id="attrs"></div>
          <div>&nbsp;</div>
          <?php } ?>
          <div>
            <label for="qty" style="width: 60px;"><b>数量:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></label>
            <input name="qty" id="qty" name="value" value="1" style="width: 40px;"/>
            <label><b>&nbsp;&nbsp;(库存:&nbsp;</b></label>
            <span id="stock"></span>
            <label><b>)</b></label>
          </div>
        </div>
      </div>
      <button onclick="add_to_cart(event, 1);" class="pure-button pure-button-active pure_button_cart"><i class="fa fa-check fa-lg"></i>&nbsp;立即购买</button>
      <button onclick="add_to_cart(event, 0);" class="pure-button pure-button-active pure_button_cart"><i class="fa fa-shopping-cart fa-lg"></i>&nbsp;加入购物车</button>
      <div>&nbsp;</div>
    </td>
    <td class="more" rowspan="2"><?php include PLGN_DIR . basename(dirname(__FILE__)) . '/inc.rightbar.php'; ?></td>
  </tr>
  <tr>
    <td colspan=2 class="tabs">
      <div id="tabs" style="width: 710px">
        <ul>
          <li><a href="#tabs-1" class="tab">详细情况</a></li>
          <li><a href="#tabs-2" class="tab">咨询我们</a></li>
        </ul>
        <div id="tabs-1"><?php echo $data[0]->description; ?></div>
        <div id="tabs-2">
          <div class="pure-form pure-form-aligned pure_form_extra">
            <div class="pure-control-group">
              <label>咨询内容</label>
              <label><textarea id="enq_content" style="width: 450px; height: 300px; resize: none;"></textarea></label>
            </div>
            <div class="pure-control-group">
              <label>联系方式(邮箱/电话)</label>
              <input id="enq_contact" type="text" class="pure-input-1-2"></input>
            </div>
            <div class="pure-control-group">
              <label>&nbsp;</label>
              <button class="pure-button pure-input-1-2 pure-button-primary" onclick="send_enquiry();">提交</button>
            </div>
          </div>
        </div>
      </div>
    </td>
  </tr>
</table>
<div>&nbsp;</div>
<div id="dialog_warning" class="pure-form" style="display: none;" title="有问题...">
  <div id="warning" style="font-weight: bold; font-size: 14px; color: red;"></div>
</div>

<div id="dialog_cart" class="pure-form" style="display: none;" title="商品已成功加入购物车">
  <div id="cart" style="font-weight: bold; font-size: 14px; color: green;"></div>
</div>

<script type="text/javascript">
  var __user = JSON.parse('<?php echo addslashes(json_encode($user)); ?>');
  var __cart = JSON.parse('<?php echo addslashes(json_encode($cart)); ?>');
  var __currs = JSON.parse('<?php echo addslashes(json_encode($currs)); ?>');
  var __attrs = JSON.parse('<?php echo addslashes(json_encode($attrs)); ?>');
  var __opts = JSON.parse('<?php echo addslashes(json_encode($myopts)); ?>');
  var __pdobjs = JSON.parse('<?php echo addslashes(json_encode($pdobjs)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __curr, __browsed, __stock;
  var __mkt_prc_rt = '<?php echo MKT_PRC_RT; ?>';

  $(function(){
    Utils.init_ecomm();
    
    var MIN = 1;
    $('#qty').spinner({ min: MIN });
    $('#qty').on('keyup', function(e) {
      var v = parseInt($(this).val());
      if (isNaN(v)) {
        return $(this).val(MIN);
      }
      if ($(this).val() < MIN) {
         $(this).val(MIN);
      } else {
        $(this).val(v);
      }
    });
    
    __browsed = Cookie.get_cookie('p_browsed');
    if (!__browsed) {
      __browsed = [{
        id: __data[0].id,
        name: __data[0].name
      }];
    } else {
      __browsed = JSON.parse(__browsed);
      Utils.splice_by_id(__data[0].id, __browsed);
      __browsed.splice(0, 0, {
        id: __data[0].id,
        name: __data[0].name
      });
      if (__browsed.length > 10) {
        __browsed.splice(9, __browsed.length - 10);
      }
    }
    Cookie.set_cookie('p_browsed', JSON.stringify(__browsed), 1);
    
    $('#etalage').etalage({
      thumb_image_width: 320,
      thumb_image_height: 240,
      source_image_width: 800,
      source_image_height: 600,
      small_thumbs: 5
    });
    $('#tabs').tabs({ show: { effect:'blind', duration: 300 }, heightStyle: 'auto' });

    reset();
    render();
  });

  function reset() {
    Utils.set_attrs(__attrs, __opts);
    for (var idx in __attrs) {
      var itm = __attrs[idx];
      itm.__opts[0].__s = 1;
    }
  };

  function render() {
    render_attrs();
  };

  function render_data() {
    var attr_opt_id = __get_selected('id').join('-');
    __data[0].__op = __data[0].price;
    if (__attrs.length != 0) {
      for (var idx in __pdobjs) {
        var itm = __pdobjs[idx];
        if (itm.attr_opt_id == attr_opt_id) {
          __data[0].__op = parseFloat(__data[0].__op, 10) + parseFloat(itm.price, 10);
          __stock = itm.stock;
        }
      }
    } else {
      __stock = __data[0].stock;
    }
    
    if (__data[0].enabled_stock == 0) {
      $('#stock').html('不限量');
    } else {
      for (var idx in __cart) {
        var itm = __cart[idx];
        if (itm.product_id == __data[0].id && itm.attr_opt_id == attr_opt_id) {
          __stock -= itm.quantity;
        }
      }
      $('#stock').html(__stock);
    }
    __data[0].__op = Utils.get_price(__currs, __data[0].curr, __curr.title, __data[0].__op, null);
    __data[0].__fp = Utils.get_price(__currs, __curr.title, __curr.title, __data[0].__op, __data[0].enabled_member == 1 ? (__user ? __user.__discount : null) : null);
    $('.mkt').empty();
    $('.sale').empty();
    $('.save').empty();
    $('.mkt').append(accounting.formatMoney(__data[0].__op * __mkt_prc_rt, __curr.dollar_symbol));
    $('.sale').append(accounting.formatMoney(__data[0].__fp, __curr.dollar_symbol));
    $('.save').append(accounting.formatMoney(__data[0].__op * __mkt_prc_rt - __data[0].__fp, __curr.dollar_symbol));
  };
  
  function render_attrs() {
    $('#attrs').empty();
    for (var idx in __attrs) {
      var itm = __attrs[idx];
      $('#attrs').append('<div style="width: 60px; font-weight: bold; float: left;">' + itm.name + '</div>');
      
      for (var idx2 in itm.__opts) {
        var itm2 = itm.__opts[idx2];
        $('#attrs').append('<div onclick="update_selected(' + itm2.id + ');" class="form3' + ((itm2.__s && itm2.__s == 1) ? ' hi' : '') + '" title="' + itm2.name + '">' + itm2.name + '</div>');
      }
      $('#attrs').append('<div style="clear: both;">&nbsp;</div>');
    }
    $('#selected').html(__get_selected('name').join('+'));
    render_data();
  };

  function add_to_cart(ev, is_buynow) {
    if (__data[0].enabled_stock == 1 && $('#qty').val() > parseFloat($('#stock').html(), 10)) {
      $('#warning').empty();
      $('#warning').append('库存不足');
      $('#dialog_warning').dialog({
        position: {
          my: 'left+0 bottom+0',
          of: ev.target
        },
        buttons: {
          '关闭': function() { 
            $(this).dialog('close');
          }
        }
      });
      return;
    }
    
    var obj = {
      product_id: __data[0].id,
      customer_id: 0,
      order_id: 0,
      name: __data[0].name,
      curr: __curr.title,
      weight: __data[0].weight,
      price: __data[0].__op,
      quantity: $('#qty').val(),
      total: $('#qty').val() * __data[0].__fp,
      attr_opt_id: __get_selected('id').join('-'),
      attr_opt_code: __get_selected('name').join('+'),
      __stock: __stock,
      __enabled_member: __data[0].enabled_member,
      __enabled_stock: __data[0].enabled_stock
    };
    
    var ex = 0, qty = 0;
    for (var idx in __cart) {
      var itm = __cart[idx];
      qty += parseFloat(itm.quantity, 10);
      if (itm.product_id == obj.product_id && itm.attr_opt_id == obj.attr_opt_id) {
        itm.quantity = parseFloat(itm.quantity, 10) + parseFloat(obj.quantity, 10);
        itm.total = __data[0].__fp * itm.quantity;
        ex = 1;
      }
    }
    if (ex == 0) {
      __cart.push(obj);
    }

    Ajax.request(
      __requrl + 'update_cart',
      'req=' + Utils.encodeURI(JSON.stringify(__cart)),
      function(rslt) {
        Utils.set_cartnum(__cart);
        render();
        if (is_buynow == 1) {
          Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=index_login');
          return;
        } 
        $('#cart').empty();
        $('#cart').append('您购物车目前有' + __cart.length + '种商品, 共' + (parseFloat(qty, 10) + parseFloat(obj.quantity, 10)) + '件物品');
        $('#dialog_cart').dialog({
          position: {
            my: 'left+0 bottom+0',
            of: ev.target
          },
          buttons: {
            '继续购物': function() { 
              $(this).dialog('close');
            },
            '前往购物车': function() { 
              Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=index_cart');
            }
          }
        });
      },
      null
    );
  };

  function update_selected(id) {
    var opt = Utils.get_by_id(id, __opts);
    var attr = Utils.get_by_id(opt.product_attr_id, __attrs);
    for (var idx in attr.__opts) {
      var itm = attr.__opts[idx];
      if (itm.id == id) {
        itm.__s = 1;
      } else {
        delete itm.__s;
      }
    }
    render();
  };

  function update_curr(id) {
    __curr = Utils.get_by_id(id, __currs);
    Cookie.set_cookie('curr', JSON.stringify(__curr), 1);
    render();
  };

  function __get_selected(attr_name) {
    var opts = [];
    for (var idx in __attrs) {
      var itm = __attrs[idx]
      for (var idx2 in itm.__opts) {
        var itm2 = itm.__opts[idx2];
        if (itm2.__s && itm2.__s == 1) {
          opts.push(itm2[attr_name]);
        }
      }
    }
    return opts;
  };

  function send_enquiry() {
    var req = {
      product: __data[0].name,
      content: $('#enq_content').val(),
      contact: $('#enq_contact').val()
    };
    Ajax.request(
      __requrl + 'send_enquiry',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        $('#enq_content').val('');
        $('#enq_contact').val('')
      },
      null
    );
  };
</script>
